#include <iostream>
#include <errno.h>

using namespace std;

#include "tcp4.h"

TCP4::TCP4():Socket(AF_INET, SOCK_STREAM){}

TCP4::TCP4(int sock):Socket(){

  m_family = AF_INET;

  m_type = SOCK_STREAM;

  m_sockfd = sock;

}


int TCP4::Listen(){

  int err = listen(m_sockfd, BACK_LOG_NUM);

  if(err == -1){
    
    cout << strerror(errno) << endl;

  }
  else{

    cout << "Socket listening" << endl;


  }

  return err;

}

Socket* TCP4::Accept(){

  int sock = accept(m_sockfd, (sockaddr*)&m_peer_addr, &peer_addr_length);


  if(sock == -1){//error on accept

    cout << strerror(errno)  << endl;
    return NULL;

  }
  else{

    TCP4* socket = new TCP4(sock);

    socket->SetPeerAddress(m_peer_addr);

    cout << "Connection Accepted" << endl;

    return socket;

  }

}

int TCP4::Connect(char* address, int port){

  m_peer_addr.sin_port = htons(port);
  m_peer_addr.sin_family = AF_INET;
  inet_pton(AF_INET, address, &m_peer_addr.sin_addr);
 
  int err = connect(m_sockfd, (sockaddr*)&m_peer_addr, sizeof(struct sockaddr));



  if(err == -1){

    cout << strerror(errno) << endl;
    return err;

  }
  else{

    return err;

  }

}

int TCP4::Receive(void* buffer, int length){

  int err = recv(m_sockfd, buffer, length, 0);


  if(err == -1){

    cout << strerror(errno) << endl;

  }

    return err;


}

int TCP4::Send(const void* buffer, int length){

  int err = send(m_sockfd, buffer, length, 0);

  if(err == -1){

    cout << strerror(errno) << endl;

  }
 
  return err;


}
